package org.subject.controller;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.subject.dto.MessageAndUser;
import org.subject.entity.Article;
import org.subject.entity.Page;
import org.subject.entity.User;
import org.subject.service.ArticleService;
import org.subject.utils.ResponseUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 通知消息控制器
 * Created by kai on 2017/5/11.
 */
@Controller
@RequestMapping("/article")
public class ArticleController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ArticleService articleService;

    /**
     * 返回竞赛通知管理页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/articlePage")
    public String getArticleManager(Model model) {
        int pages = 1;
        List<Article> articleList = articleService.queryArticleList("", pages);
        model.addAttribute("articleList", articleList);
        int count = articleService.queryArticleCount("");
        Page page = new Page();
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        return "articleManage";
    }

    /**
     * 保存或修改
     *
     * @param article
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Model model, Article article, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        logger.info(article.toString());
        if (request.getSession().getAttribute("user") != null) {
            User user = (User) request.getSession().getAttribute("user");
            article.setUserId(user.getUserId());
        }
        int code = articleService.insertArticle(article);
        logger.info("返回码：" + code);
        if (articleService.selectListArticle() != null) {
            for (Article article1 : articleService.selectListArticle()) {
                logger.info(article1.toString());
            }
        }
        List<Article> articleList = articleService.selectListArticle();
        model.addAttribute("articleList", articleList);
        return "articleManage";
    }

    /**
     * 根据id查找
     *
     * @param id
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    public String findById(Model model, @RequestParam(value = "id") String id,
                           HttpServletResponse response) throws Exception {
        Article article = articleService.selectByPrimaryKey(Long.valueOf(id));
        logger.info(article.toString());
        /*JSONObject jsonObject = JSONObject.fromObject(article);
        ResponseUtil.write(response, jsonObject);*/
        model.addAttribute("article", article);
        return "articleDetail";
    }

    @RequestMapping(value = "/deleteById", method = RequestMethod.GET)
    public String deleteById(Model model, @RequestParam(value = "id") String id,
                             HttpServletResponse response) throws Exception {
        int code = articleService.deleteArticleById(id);
        int pages = 1;
        List<Article> articleList = articleService.queryArticleList("", pages);
        model.addAttribute("articleList", articleList);
        int count = articleService.queryArticleCount("");
        Page page = new Page();
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        return "articleManage";
    }

    @RequestMapping("/articleList")
    public String articleList(Model model) {
        int pages = 1;
        List<Article> articleList = articleService.queryArticleList("", pages);
        model.addAttribute("articleList", articleList);
        int count = articleService.queryArticleCount("");
        Page page = new Page();
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        return "articleList";
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public String messageListBypage(Model model, @RequestParam("page") String current, HttpServletRequest req) {
        int pages;
        Pattern pattern = Pattern.compile("[0-9]{1,9}");
        if (current == null || !pattern.matcher(current).matches()) {
            pages = 1;
        } else {
            pages = Integer.valueOf(current);
        }
        List<Article> articleList = articleService.queryArticleList("", pages);
        int count = articleService.queryArticleCount("");
        Page page = new Page();
        page.setCurrentPage(pages);
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        model.addAttribute("articleList", articleList);
        return "articleList";
    }

    @RequestMapping(value = "/managePage", method = RequestMethod.GET)
    public String articleManageByPage(Model model, @RequestParam("page") String current) {
        int pages;
        Pattern pattern = Pattern.compile("[0-9]{1,9}");
        if (current == null || !pattern.matcher(current).matches()) {
            pages = 1;
        } else {
            pages = Integer.valueOf(current);
        }
        List<Article> articleList = articleService.queryArticleList("", pages);
        model.addAttribute("articleList", articleList);
        int count = articleService.queryArticleCount("");
        Page page = new Page();
        page.setCurrentPage(pages);
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        return "articleManage";
    }
}
